package com.performax.service;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.performax.database.Vo.*;
import com.performax.database.Dao.*;
import com.performax.utils.Oh2gameUtils;


@Controller
@RequestMapping("/app/api/community")
public class OheGameCommController {

	private static final Logger logger = LoggerFactory.getLogger(OheGameCommController.class);
	
	@Resource(name = "oh2gameCommunityDao")
	private Oh2GameCommunityDao oh2gameCommunityDao;
	
	@Resource(name = "oh2gameGlobalDao")
	private	Oh2GameGlobalDao oh2gameGlobalDao;
	
	@Resource(name = "oh2gameMypageDao")
	private Oh2GameMypageDao oh2gameMypageDao;
	
	
	@RequestMapping(value="/boardlist")
	@ResponseBody
	public Object boardlist(@RequestParam(value="authKey", 		required=true) 				String authKey
							,@RequestParam(value="mediaCd", 	defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", 		required=true) 				String userId
							,@RequestParam(value="gid", 		defaultValue="XXXXXXXXXX") 	String gid
							,@RequestParam(value="reqPage", 	defaultValue="1") 			int reqPage
							,@RequestParam(value="listPerPage", defaultValue="30") 			int listPerPage
							,@RequestParam(value="searchType", 	defaultValue="A") 			String searchType
							,@RequestParam(value="search", 		required=false) 			String search
							,@RequestParam(value="boardType", 	defaultValue="F") 			String boardType
							,@RequestParam(value="sortType", 	defaultValue="new") 		String sortType
							,HttpServletRequest req )
	{
		//System.out.println(oh2gameGlobalDao.getFileSavePath("BOARD_ATTACH_FILE_PATH"));
		int start = (reqPage * listPerPage - listPerPage);
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		param.put("boardType", boardType);
		param.put("search", search);
		param.put("searchType", searchType);
		param.put("listPerPage", listPerPage);
		param.put("start", start);
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		param.put("sortType", sortType);
		
		//get Notice List
		List<NoticeInfoVo> noticeList	=	oh2gameCommunityDao.getNoticeList();
		
		//get Board List
		List<BoardInfoVo> boardList	=	oh2gameCommunityDao.getBoardList(param);
		
		//get board count
		int listCnt	=	oh2gameCommunityDao.getBoardListCnt(param);
		
		String lastPage	=	"Y";
		
		if(listCnt > (reqPage*listPerPage)){
			lastPage	=	"N";
		}
		
		//set result
		Hashtable<String, Object> result	=	new	Hashtable<String, Object>();
		result.put("resType","boardlist");
		result.put("result","1000");
		result.put("listCnt", boardList.size());
		result.put("pageNo", reqPage);
		result.put("lastPage", lastPage);
		result.put("boardInfo", boardList);
		result.put("noticeListCnt", noticeList.size());
		result.put("noticeInfo", noticeList);
		
		result.put("resultMessage", param);
		
		logger.debug("/boardlist", result);
		
		return result;
	}
	
	@RequestMapping(value="/boarddetail")
	@ResponseBody
	public Object boarddetail(@RequestParam(value="authKey", 		required=true) 				String authKey
								,@RequestParam(value="mediaCd", 	defaultValue="mcdoheapp")	String mediaCd
								,@RequestParam(value="userId", 		required=true) 				String userId
								,@RequestParam(value="gid", 		defaultValue="XXXXXXXXXX") 	String gid
								,@RequestParam(value="boardId", 	required=true) 				int boardId
								,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		param.put("boardId", boardId);
		
		
		Hashtable<String, Object> result	=	new	Hashtable<String, Object>();
		
		BoardDetailVo	boardInfo	=	oh2gameCommunityDao.getBoardDetail(param);
		
		if(boardInfo.getAttachType().equals("Y")){
			List<AttachInfoVo> attachFileList	=	oh2gameCommunityDao.getAttachFileList(boardId);
			result.put("attachInfo", attachFileList);
		}
		
		String profileUrl	=	oh2gameMypageDao.getProfile(userId);
		if(profileUrl	==	null)	profileUrl	=	"";
		
		result.put("resType","boarddetail");
		result.put("result","1000");
		result.put("boardId",boardId);
		result.put("gender",boardInfo.getGender());
		result.put("writerId",boardInfo.getWriterId());
		result.put("writerName",boardInfo.getWriterName());
		result.put("profileUrl",profileUrl);
		result.put("viewCnt",boardInfo.getViewCnt());
		result.put("replyCnt",boardInfo.getReplyCnt());
		result.put("recCnt",boardInfo.getRecCnt());
		result.put("repCnt",boardInfo.getRepCnt());
		result.put("regDt",boardInfo.getRegDt());
		result.put("contents",boardInfo.getContents());
		result.put("youTubeUrl",boardInfo.getYouTubeUrl());
		result.put("recType",boardInfo.getRecType());
		result.put("reportType",boardInfo.getReportType());
		result.put("title", boardInfo.getTitle());
		result.put("contentsOrder", boardInfo.getContentsOrder());
		
		result.put("resultMessage", param);
		
		logger.debug("/boarddetail", result);
		
		return result;
	}
	
	@RequestMapping(value="/boardreg")
	@ResponseBody
	public Object boardreg(@RequestParam(value="authKey", 			required=true) 				String authKey
							,@RequestParam(value="mediaCd", 		defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", 			required=true) 				String userId
							,@RequestParam(value="gid", 			defaultValue="XXXXXXXXXX") 	String gid
							,@RequestParam(value="boardType", 		required=true) 				String boardType
							,@RequestParam(value="title", 			required=true) 				String title
							,@RequestParam(value="contents", 		required=true) 				String contents
							,@RequestParam(value="uploadCnt", 		defaultValue="0") 			int uploadCnt
							,@RequestParam(value="youTubeUrl", 		required=false) 			String youTubeUrl
							,@RequestParam(value="regType", 		required=true) 				String regType
							,@RequestParam(value="boardId", 		defaultValue="0") 			int boardId
							,@RequestParam(value="delFile",			required=false)				String delFile
							,@RequestParam(value="contentsOrder",	required=true)				String contentsOrder
							,HttpServletRequest req ) throws Exception
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		/**
		 * file upload
		 */
		String	attType	=	"N";
		if(uploadCnt	>	0){
			attType	=	"Y";
			Calendar now	=	Calendar.getInstance();
			String year		=	String.valueOf(now.get(Calendar.YEAR));
			int nMonth	=	now.get(Calendar.MONTH)+1;
			String month	=	"";
			if(nMonth	<	10){
				month	=	"0";
			}
			month	=	month+String.valueOf(nMonth);
			
			//String month	=	String.valueOf(now.get(Calendar.MONTH));
			//String date		=	String.valueOf(now.get(Calendar.DATE));
			//String hour		=	String.valueOf(now.get(Calendar.HOUR));
			//String minute	=	String.valueOf(now.get(Calendar.MINUTE));
			
			String	serverBasePath	=	oh2gameGlobalDao.getFileSavePath("FILE_SAVE_BASE_PATH");
			String uploadPath	=	new StringBuffer()
				.append(oh2gameGlobalDao.getFileSavePath("BOARD_ATTACH_FILE_PATH"))
				.append(year).append("/")
				.append(month).append("/").toString();
				
			String serviceDomain	=	oh2gameGlobalDao.getFileSavePath("AWS_IMAGE_SERVER_DOMAIN");
			//DB 조회로 변경 필요
			String bucketName	=	"oh2game";
			
			MultipartHttpServletRequest multipart	=	(MultipartHttpServletRequest)req;
			Map<String, MultipartFile>	filemap	=	multipart.getFileMap();
			
			
			File upPath	=	new	File(serverBasePath+uploadPath);
			
			if(!upPath.exists()){
				upPath.mkdir();
			}
			
			List<AttachInfoVo> fileResult	=	new	Vector<AttachInfoVo>();
			
			//File	directory	=	new	File("/var/www/html/appimage/boardAttachFile/2015/05/");
			List<File> files	=	new	ArrayList<File> ();
			
			for(int i = 0 ; i < uploadCnt ; i++){
				MultipartFile	file	=	filemap.get("upFile"+(i+1));
				File	f	=	new	File(file.getOriginalFilename());
				file.transferTo(f);
				files.add(f);
				//String orgName	=	URLDecoder.decode(new String(file.getOriginalFilename().getBytes()), "UTF-8");
				
				//String serverName	=	new StringBuffer().append(System.currentTimeMillis()).append(orgName.substring(orgName.lastIndexOf("."))).toString();
				//FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(serverBasePath+uploadPath+serverName));
				
				//String url		=	"http://"+oh2gameGlobalDao.getFileSavePath("SERVICE_DOMAIN")+"/"+uploadPath+serverName;
				
				/*AttachInfoVo	attachInfo	=	new	AttachInfoVo();
				attachInfo.setOrgName(orgName);
				attachInfo.setUrl(url);
				
				fileResult.add(attachInfo);	*/
			}
			List<HashMap<String, String>> transferResult	=	new	ArrayList<HashMap<String, String>> ();
			
			try{
				transferResult	=	Oh2gameUtils.transferS3(files, uploadPath, bucketName, serviceDomain);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			for(HashMap<String, String> fileInfo	:	transferResult){
				AttachInfoVo	attachInfo	=	new	AttachInfoVo();
				attachInfo.setOrgName(fileInfo.get("orgName"));
				attachInfo.setUrl(fileInfo.get("url"));
				
				fileResult.add(attachInfo);
			}
			
			param.put("attFileInfo", fileResult);
			
		}
		/*
		 * file upload
		 */
		param.put("attType",		attType);
		param.put("authKey", 		authKey);
		param.put("mediaCd", 		mediaCd);
		param.put("userId", 		userId);
		param.put("gid", 			gid);
		param.put("boardType", 		boardType);
		param.put("title", 			title);
		param.put("contents", 		contents);
		param.put("uploadCnt", 		uploadCnt);
		param.put("youTubeUrl", 	youTubeUrl);
		param.put("regType", 		regType);
		param.put("boardId", 		boardId);
		param.put("contentsOrder", 	contentsOrder);

		System.out.println("regType : "+regType);
		if(regType.equals("C")){
			oh2gameCommunityDao.regBoard(param);
		}else{
			param.put("delFile", delFile);
			oh2gameCommunityDao.updBoard(param);
		}
		
		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","boardreg");
		result.put("boardId",boardId);
		result.put("regType",regType);
		result.put("result","1000");
		
		result.put("resultMessage", param);
		return result;
	}
	
	
	
	@RequestMapping(value="/boarddelete")
	@ResponseBody
	public Object boarddelete(	@RequestParam(value="authKey", 		required=true) 				String authKey
								,@RequestParam(value="mediaCd", 	defaultValue="mcdoheapp")	String mediaCd
								,@RequestParam(value="userId", 		required=true) 				String userId
								,@RequestParam(value="gid", 		defaultValue="XXXXXXXXXX") 	String gid
								,@RequestParam(value="boardId", 	required=true) 				int boardId
								,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", 	gid);
		param.put("boardId", boardId);
		
		oh2gameCommunityDao.delBoard(boardId);
		
		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","boarddelete");
		result.put("boardId",boardId);
		result.put("result","1000");
		
		result.put("resultMessage", param);
		return result;
	}
	
	@RequestMapping(value="/replylist")
	@ResponseBody
	public Object replylist( @RequestParam(value="authKey", required=true) 				String authKey
							,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", required=true) 				String userId
							,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
							,@RequestParam(value="boardId", required=true) 				int boardId
							,@RequestParam(value="reqPage", defaultValue="1") 			int reqPage
							,@RequestParam(value="listPerPage", defaultValue="30") 		int listPerPage
							,HttpServletRequest req )
	{
		int start = (reqPage * listPerPage - listPerPage);
		
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		param.put("boardId", boardId);
		param.put("reqPage", reqPage);
		param.put("listPerPage", listPerPage);
		param.put("start", start);
		
		List<ReplyInfoVo> replyList	=	oh2gameCommunityDao.getBoardReplyList(param);
		List<Integer>		reportList	=	oh2gameCommunityDao.getBoardReplyReportList(userId, boardId);
		List<Integer>		recList	=	oh2gameCommunityDao.getBoardReplyRecList(userId, boardId);
		
		int listCnt	=	oh2gameCommunityDao.getBoardReplyListCnt(boardId);
				
		String lastPage	=	"Y";
				
		if(listCnt > (reqPage*listPerPage)){
			lastPage	=	"N";
		}
		
		for(int i = 0 ; i < replyList.size() ; i++){
			ReplyInfoVo replyInfo	=	replyList.get(i);
			
			if(reportList.contains(replyInfo.getReplyId())){
				replyInfo.setReportType("Y");
			}
			
			if(recList.contains(replyInfo.getReplyId())){
				replyInfo.setRecType("Y");
			}
		}
		
		Hashtable<String, Object> result	=	new	Hashtable<String, Object>();
		result.put("resType","replylist");
		result.put("result","1000");
		result.put("boardId",boardId);
		result.put("listCnt",replyList.size());
		result.put("pageNo","1");
		result.put("lastPage",lastPage);
		result.put("replyInfo",replyList);
		
		result.put("resultMessage", param);
		
		logger.debug("/replylist", result);
		
		return result;
	}
	
	
	@RequestMapping(value="/replyreg")
	@ResponseBody
	public Object replyreg(@RequestParam(value="authKey", required=true) 				String authKey
							,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", required=true) 				String userId
							,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
							,@RequestParam(value="boardId", required=true) 				int boardId
							,@RequestParam(value="upperId", defaultValue="0") 			int upperId
							,@RequestParam(value="contents", required=true) 			String contents
							,@RequestParam(value="regType", required=true) 				String regType
							,@RequestParam(value="replyId", defaultValue="0") 			int replyId
							,HttpServletRequest req )
	{
		
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		param.put("boardId", boardId);
		param.put("upperId", upperId);
		param.put("contents", contents);
		param.put("regType", regType);
		param.put("replyId", replyId);
		
		if(regType.equals("C")){
			oh2gameCommunityDao.regBoardReply(param, upperId, boardId);
			
			HashMap<String, Object> pushParam	=	new	HashMap<String, Object> ();
			
			if(upperId	==	0){
				pushParam.put("targetEventType", "BOARD_REPLY");
				pushParam.put("targetEventID", boardId);
			}else{
				pushParam.put("targetEventType", "BOARD_REPLY1");
				pushParam.put("targetEventID", upperId);
			}
			
			oh2gameGlobalDao.regPushTarget(pushParam);
		}else{
			oh2gameCommunityDao.updBoardReply(param);
		}
		
		
		
		Hashtable<String, Object> result	=	new	Hashtable<String, Object>();
		result.put("resType","replyreg");
		result.put("result","1000");
		result.put("replyId",replyId);
		
		result.put("resultMessage", param);
		
		logger.debug("/replyreg", result);
		return result;
	}
	
	@RequestMapping(value="/replydelete")
	@ResponseBody
	public Object replydelete(@RequestParam(value="authKey", 		required=true) 				String authKey
								,@RequestParam(value="mediaCd", 	defaultValue="mcdoheapp")	String mediaCd
								,@RequestParam(value="userId", 		required=true) 				String userId
								,@RequestParam(value="gid", 		defaultValue="XXXXXXXXXX") 	String gid
								,@RequestParam(value="replyId", 	required=true) 				int replyId
								,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", 	gid);
		param.put("replyId", replyId);
		
		oh2gameCommunityDao.delBoardReply(replyId);

		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","replydelete");
		result.put("replyId",replyId);
		result.put("result","1000");
		
		result.put("resultMessage", param);
		return result;
	}	
	
	@RequestMapping(value="/recreport", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object recreport(@RequestParam(value="authKey", required=true) 			String authKey
						,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
						,@RequestParam(value="userId", required=true) 				String userId
						,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
						,@RequestParam(value="type", required=true) 				String type
						,@RequestParam(value="target", required=true) 				String target
						,@RequestParam(value="boardId", defaultValue="0") 			int boardId
						,@RequestParam(value="replyId", defaultValue="0") 			int replyId
						,@RequestParam(value="reasonCheck", required=true) 			String reasonCheck
						,@RequestParam(value="reasonCmt", required=false) 			String reasonCmt
						,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", 	gid);
		param.put("boardId", boardId);
		param.put("replyId", replyId);
		param.put("type", type);
		param.put("target", target);
		param.put("reasonCheck", reasonCheck);
		param.put("reasonCmt", reasonCmt); 
		
		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","recreport");
		
		if(type.equals("REC")){
			int recCnt	=	oh2gameCommunityDao.recommend(param);
			result.put("recCnt",	recCnt);
			
		}else{
			StringBuffer	reason	=	new	StringBuffer().append(reasonCheck);
			if(reasonCmt!=null)	reason.append("||").append(reasonCmt);
			
			param.put("reason", reason.toString());
			
			oh2gameCommunityDao.report(param);
			
			HashMap<String, Object> pushParam	=	new	HashMap<String, Object> ();
			if(target.equals("BO")){
				pushParam.put("targetEventType", "BOARD_REPORT");
				pushParam.put("targetEventID", boardId);
			}else if(target.equals("BR")){
				pushParam.put("targetEventType", "BOARD_REPLY_REPORT");
				pushParam.put("targetEventID", replyId);
			}
			oh2gameGlobalDao.regPushTarget(pushParam);
			
		}
		
		
		
		
		result.put("boardId",boardId);
		result.put("replyId",replyId);
		result.put("type",type);
		result.put("target",target);
		result.put("result","1000");
		
		 
		result.put("resultMessage", param);
		return result;
	}
	
	@RequestMapping(value="/friendlist")
	@ResponseBody
	public Object friendlist(@RequestParam(value="authKey", required=true) 				String authKey
							,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", required=true) 				String userId
							,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
							,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		
		
		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","friendlist");
	
		
		List<FriendInfoVo>	friendList	=	oh2gameCommunityDao.getFriendList();
		String				status		=	"N";
		if(friendList	==	null){
			result.put("result", 1000);
			result.put(status, status);
			result.put("listCnt", 0);
			result.put("resultMessage", "result not found");
		}
		
		for(int i = 0 ; i < friendList.size(); i++){
			FriendInfoVo	friendInfo	=	friendList.get(i);
			if(friendInfo.getId().equals(userId)){
				friendList.remove(i);
				status=	"Y";
				break;
			}
		}
		
		result.put("result", "1000");
		result.put("status", status);
		result.put("listCnt", friendList.size());
		result.put("friendInfo", friendList);
				
		result.put("resultMessage", param);
		return result;
	}

	@RequestMapping(value="/friendreg")
	@ResponseBody
	public Object friendreg(@RequestParam(value="authKey", required=true) 				String authKey
							,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
							,@RequestParam(value="userId", required=true) 				String userId
							,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
							,@RequestParam(value="regType", required=true) 				String regType
							,HttpServletRequest req )
	{
		HashMap<String, Object> param	=	new	HashMap<String, Object>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", gid);
		param.put("regType", regType);
		
		oh2gameCommunityDao.friendreg(regType, userId);
		
		HashMap<String, Object> result	=	new	HashMap<String, Object>();
		result.put("resType","friendreg");
		result.put("result","1000");
		result.put("status","Y");
		
		result.put("resultMessage", param);
		return result;
	}
	
	/*@RequestMapping(value="/imageupload")
	@ResponseBody
	public Object imageupload(	@RequestParam(value="authKey", required=true) 				String authKey
								,@RequestParam(value="mediaCd", defaultValue="mcdoheapp")	String mediaCd
								,@RequestParam(value="userId", required=true) 				String userId
								,@RequestParam(value="gid", defaultValue="XXXXXXXXXX") 		String gid
								,HttpServletRequest req )
	{
		Hashtable<String, Object> result	=	new	Hashtable<String, Object>();
		result.put("resType","imageuplaod");
		result.put("result","1000");
		result.put("attachFile1","http://www.oh2game.com/image/1.png");
		result.put("attachFile2","http://www.oh2game.com/image/2.png");
		result.put("attachFile3","http://www.oh2game.com/image/3.png");
		result.put("attachFile4","http://www.oh2game.com/image/4.png");
		
		
		Hashtable<String, String> param	=	new	Hashtable<String, String>();
		
		param.put("authKey", authKey);
		param.put("mediaCd", mediaCd);
		param.put("userId", userId);
		param.put("gid", 	gid);
		
		
		result.put("resultMessage", param);
		return result;
	}
	*/
	
}

